import os
import launch.event_handlers
from launch import LaunchDescription
from launch.substitutions import LaunchConfiguration
from ament_index_python.packages import get_package_share_directory
import launch
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.actions import IncludeLaunchDescription
from launch_ros.actions import Node

def generate_launch_description():
    package_path = get_package_share_directory("description_pkg")

    launch_file_dir = os.path.join(package_path, 'launch')
    world = os.path.join(
        package_path,
        'worlds',
        'empty.world'
    )

    use_sim_time = LaunchConfiguration('use_sim_time', default='true')
   
   
    # 通过 IncludeLaunchDescription 包含另外一个 launch 文件
    launch_gazebo = launch.actions.IncludeLaunchDescription(
        PythonLaunchDescriptionSource([get_package_share_directory(
            'gazebo_ros'), '/launch', '/gazebo.launch.py']),
      	# 传递参数
        launch_arguments={'use_sim_time': use_sim_time,'world':world}.items()
    )
   
    # 请求 Gazebo 加载机器人
    spawn_agv_robot_cmd = IncludeLaunchDescription(
        PythonLaunchDescriptionSource(
            os.path.join(launch_file_dir, 'agv_robot.launch.py')
        )
    )

    spawn_pallet = Node(
        package='gazebo_ros',
        executable='spawn_entity.py',
        name='spawn_entity',
        arguments=[
            '-file', os.path.join(package_path,'models','pallet.sdf'),
            '-entity', 'pallet',
            '-x', '-2.8',
            '-y', '0.0',
            '-z', '0.0', 
            '-Y', '0.0'
        ]
    )
    
    ld = LaunchDescription()
    # gazebo 仿真
    ld.add_action(launch_gazebo)
    ld.add_action(launch.actions.TimerAction(period=2.0,actions=[spawn_agv_robot_cmd]))
    ld.add_action(launch.actions.TimerAction(period=3.0,actions=[spawn_pallet]))
    return ld
